# This is a sample Python script.

import os
import shutil

from openpyxl import Workbook, load_workbook
from natsort import ns, natsorted

from PyQt5 import QtWidgets
from PyQt5.QtGui import QPainter, QPixmap, QColor, QFont
from PyQt5.QtWidgets import (QGraphicsPixmapItem, QGraphicsScene, QGraphicsTextItem, QStyleFactory)

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
from MAINWINDOWS import Ui_MainWindow

# excel表格第一个sheet，主要记录配置文件
table_name = r"迪文图片处理表格.xlsx"
sheet_name = r"配置表格"
config_table = ["源文件夹路径+文件名", "目标文件夹路径+文件名", "14号文件名", "字符串文件路径+文件名", "语言对应列"]
define_config_table = [r".\DWIN_SET", r".\DWIN_SET1", r"14ShowFile.bin", r".\APPSTR.xlsx", 2]
datasheet_name = r"数据表格"
dataconfig_table = ["图号", "控件编号", "控件类型", "X", "Y", "字体大小/图标库", "文本颜色", "数据", "对齐方式", "文本框宽度"]

source_dir = define_config_table[0]
target_dir = define_config_table[1]
display_File = define_config_table[2]
table_File = define_config_table[3]


class Ui_Setup(Ui_MainWindow):
    def __init__(self):
        super(Ui_MainWindow, self).__init__()
        self.scene_img = QGraphicsScene()
        self.language = 2
        global table_File
        global source_dir
        global target_dir
        global display_File

    def start(self):
        print("start")
        self.pushButton.clicked.connect(self.table_init)
        self.pushButton_1.clicked.connect(self.read)
        self.pushButton_2.clicked.connect(self.preview)

    def table_init(self):
        if os.path.exists(r".\{}".format(table_name)):
            os.remove(r".\{}".format(table_name))

        new = Workbook()

        newsheet = new.create_sheet(sheet_name, 0)
        for each in range(0, len(config_table)):
            newsheet.cell(row=each + 1, column=1).value = config_table[each]
            newsheet.cell(row=each + 1, column=2).value = define_config_table[each]

        newsheet = new.create_sheet(datasheet_name, 1)
        for each in range(0, len(dataconfig_table)):
            newsheet.cell(row=1, column=each + 1).value = dataconfig_table[each]
        new.save(r".\{}".format(table_name))
        self.load_config()
        self.statusBar.showMessage("初始化成功，生成初始化表格", 3000)

    def table_check(self):
        if not os.path.exists(r".\{}".format(table_name)):
            self.statusBar.showMessage("迪文图片处理表格不存在", 3000)
            return False
        return True

    def drawBackGround(self, X0: int, Y0: int, filename: str):
        self.imgShow = QPixmap()
        self.imgShow.load(filename)
        imgShowItem = QGraphicsPixmapItem()
        imgShowItem.setPixmap(QPixmap(self.imgShow))
        imgShowItem.setPos(0, 0)
        self.scene_img.setSceneRect(0, 0, self.imgShow.width(), self.imgShow.height())
        self.scene_img.addItem(imgShowItem)

    def drawIcon(self, X0: int, Y0: int, filename: str):
        imgShow = QPixmap()
        imgShow.load(filename)
        imgShowItem = QGraphicsPixmapItem()
        imgShowItem.setPixmap(QPixmap(imgShow))
        imgShowItem.setPos(X0, Y0)
        self.scene_img.addItem(imgShowItem)

    def drawIndexIcon(self, X0: int, Y0: int, index: int, file_index: int):
        if index is None or file_index is None:
            return
        for library in os.listdir(source_dir):
            if ".icl" in library:
                lib_id = ""
                for each in library:
                    if each in "0123456789":
                        lib_id = lib_id + each
                        continue
                    break
                if str(index) == index and lib_id != "":
                    library = library.split(".")[0]
                    for each in os.listdir(r".\{}".format(library)):
                        bmp_id = ""
                        for each1 in each:
                            if each1 in "0123456789":
                                bmp_id = bmp_id + each1
                                continue
                            break
                        if str(file_index) == bmp_id and bmp_id != "":
                            print(file_index)
                            self.drawIcon(X0, Y0, r".\{0}\{1}".format(library, each))
                            return

    def drawText(self, X0: int, Y0: int, text: str, size: int, color: int, alignState: str, wight: int):
        if wight == None:
            wight = 0
        f_font = QFont()
        f_font.setFamily("SimHei")
        f_font.setPointSize(size)

        TextItem = QGraphicsTextItem()
        TextItem.setPlainText(text)
        if TextItem.boundingRect().width() >= wight:
            wight = TextItem.boundingRect().width()
            TextItem.setPos(X0, Y0)
        elif alignState == "居中":
            X0 = X0 + (wight - TextItem.boundingRect().width()) / 2
            TextItem.setPos(X0, Y0)
        elif alignState == "右对齐":
            X0 = X0 + (wight - TextItem.boundingRect().width())
            TextItem.setPos(X0, Y0)
        else:
            TextItem.setPos(X0, Y0)
        R = color & 0x0000FF00
        G = color & 0x00FF0000
        B = color & 0xFF000000
        TextItem.setDefaultTextColor(QColor(R, G, B))
        TextItem.setFont(f_font)
        self.scene_img.addItem(TextItem)

    def drawIndexText(self, X0: int, Y0: int, index: str, size: int, color: int, alignState: str, wight: int):
        if index == None:
            return
        if wight == None:
            wight = 0
        wb1 = load_workbook(table_File)
        ws1 = wb1.active
        for each in ws1['A']:
            if each.value.lower() == index.lower():
                text = ws1.cell(row=each.row, column=self.language).value
                self.drawText(X0, Y0, text, size, color, alignState, wight)

    def load_config(self):
        with open(r"{0}\{1}".format(source_dir, display_File), "rb") as config_file:
            wb = load_workbook(r".\{}".format(table_name))
            ws = wb[datasheet_name]
            row = 2
            data = []
            for each in os.listdir(source_dir):
                if each.split(".")[-1].lower() == "bmp".lower() or each.split(".")[-1].lower() == "jpg".lower():
                    data.append(each)
            files_1 = natsorted(data, alg=ns.PATH)  # 要加alg=ns.PATH参数才和windows系统名称排序一致

            for background in files_1:
                picture_id = ""
                for each in background:
                    if each in "0123456789":
                        picture_id = picture_id + each
                        continue
                    break
                # 匹配图片
                picture_id = int(picture_id, 10)
                config_file.seek(0x0010 + picture_id * 4)
                data = config_file.read(1)
                P_NUM = int(data.hex(), 16)
                data = config_file.read(3)
                ADR = int(data.hex(), 16)
                config_file.seek(ADR)

                for item in range(0, P_NUM):
                    data = config_file.read(32)
                    if data[1] == 0x11:
                        ws.cell(row, 1).value = picture_id
                        ws.cell(row, 2).value = item + 1
                        ws.cell(row, 3).value = "文本显示"
                        ws.cell(row, 4).value = data[0x08] * 256 + data[0x09]
                        ws.cell(row, 5).value = data[0x08 + 2] * 256 + data[0x09 + 2]
                        ws.cell(row, 6).value = int(data[0x1A] / 2)
                        ws.cell(row, 7).value = data[0x0C] * 256 + data[0x0D]
                        ws.cell(row, 8).value = None
                        a = (data[0x1C] & (0x01 << 6)) | (data[0x1C] & (0x01 << 5))
                        a = a >> 5
                        if a == 1:
                            ws.cell(row, 9).value = "右对齐"
                        elif a == 2:
                            ws.cell(row, 9).value = "居中"
                        else:
                            ws.cell(row, 9).value = "左对齐"
                        ws.cell(row, 10).value = (data[0x12] * 256 + data[0x13])-(data[0x0E] * 256 + data[0x0F])
                        row = row + 1
                    if data[1] == 0x10:
                        ws.cell(row, 1).value = picture_id
                        ws.cell(row, 2).value = item + 1
                        ws.cell(row, 3).value = "数据变量显示"
                        ws.cell(row, 4).value = data[0x08] * 256 + data[0x09]
                        ws.cell(row, 5).value = data[0x08 + 2] * 256 + data[0x09 + 2]
                        ws.cell(row, 6).value = data[0x0F] / 2
                        ws.cell(row, 7).value = data[0x0C] * 256 + data[0x0D]
                        ws.cell(row, 8).value = None
                        a = (data[0x10] & (0x01 << 3)) | (data[0x10] & (0x01 << 2)) | (data[0x10] & (0x01 << 1)) | (data[0x10] & (0x01 << 0))
                        if a == 1:
                            ws.cell(row, 9).value = "右对齐"
                        elif a == 2:
                            ws.cell(row, 9).value = "居中"
                        else:
                            ws.cell(row, 9).value = "左对齐"
                        ws.cell(row, 10).value = None
                        row = row + 1
                    if data[1] == 0x00:
                        ws.cell(row, 1).value = picture_id
                        ws.cell(row, 2).value = item + 1
                        ws.cell(row, 3).value = "变量图标显示"
                        ws.cell(row, 4).value = data[0x08] * 256 + data[0x09]
                        ws.cell(row, 5).value = data[0x08 + 2] * 256 + data[0x09 + 2]
                        ws.cell(row, 6).value = data[0x14]
                        ws.cell(row, 7).value = None
                        ws.cell(row, 8).value = data[0x10] * 256 + data[0x11]
                        ws.cell(row, 9).value = None
                        ws.cell(row, 10).value = None
                        row = row + 1
                    if data[1] == 0x01:
                        ws.cell(row, 1).value = picture_id
                        ws.cell(row, 2).value = item + 1
                        ws.cell(row, 3).value = "动画图标显示"
                        ws.cell(row, 4).value = data[0x08] * 256 + data[0x09]
                        ws.cell(row, 5).value = data[0x08 + 2] * 256 + data[0x09 + 2]
                        ws.cell(row, 6).value = data[0x18]
                        ws.cell(row, 7).value = None
                        ws.cell(row, 8).value = data[0x12] * 256 + data[0x13]
                        ws.cell(row, 9).value = None
                        ws.cell(row, 10).value = None
                        row = row + 1
            wb.save(r".\{}".format(table_name))

    def preview(self):
        if self.table_check() is False:
            return

        wb = load_workbook(r".\{}".format(table_name))
        ws = wb[sheet_name]
        source_dir = ws['B1'].value
        target_dir = ws['B2'].value
        display_File = ws['B3'].value
        table_File = ws['B4'].value
        if source_dir is None or target_dir is None or display_File is None or table_File is None:
            self.statusBar.showMessage("配置表格为空,请检查表格", 3000)
            return
        if os.path.exists(target_dir):
            shutil.rmtree(target_dir)
        os.mkdir(target_dir)
        ws = wb[datasheet_name]
        for background in os.listdir(source_dir):
            if "bmp" not in background:
                continue
            picture_id = ""
            for each in background:
                if each in "0123456789":
                    picture_id = picture_id + each
                    continue
                break
            picture_id = int(picture_id, 10)
            # 打开背景图
            self.drawBackGround(0, 0, r"{0}\{1}".format(source_dir, background))
            start_flag = False
            a = 0
            for each in ws[2:ws.max_row]:
                if each[0].value == picture_id:
                    start_flag = True
                    if each[2].value == "文本显示" or each[2].value == "数据变量显示" or each[2].value == "变量图标显示"\
                            or each[2].value == "动画图标显示":
                        a = a + 1
                        self.drawText(each[3].value, each[4].value, str(a), 24, 0xffffff, "左对齐", 0)
                elif start_flag is True:
                    break
            # 保存图片
            pant = QPainter(self.imgShow)
            self.scene_img.render(pant)
            self.imgShow.save(r"{0}\{1}".format(target_dir, background))
            del pant
            del self.imgShow
            self.scene_img.clear()
        self.statusBar.showMessage("渲染完成", 3000)

    def read(self):
        if self.table_check() is False:
            return

        wb = load_workbook(r".\{}".format(table_name))
        ws = wb[sheet_name]
        source_dir = ws['B1'].value
        target_dir = ws['B2'].value
        display_File = ws['B3'].value
        table_File = ws['B4'].value
        self.language = ws['B5'].value

        if source_dir is None or target_dir is None or display_File is None or table_File is None:
            self.statusBar.showMessage("配置表格为空,请检查表格", 3000)
            return

        if os.path.exists(target_dir):
            shutil.rmtree(target_dir)
        os.mkdir(target_dir)
        ws = wb[datasheet_name]
        for background in os.listdir(source_dir):
            if "bmp" not in background:
                continue
            picture_id = ""
            for each in background:
                if each in "0123456789":
                    picture_id = picture_id + each
                    continue
                break
            picture_id = int(picture_id, 10)
            # 打开背景图
            self.drawBackGround(0, 0, r"{0}\{1}".format(source_dir, background))
            start_flag = False
            for each in ws[2:ws.max_row]:
                if each[0].value == picture_id:
                    start_flag = True
                    if each[2].value == "文本显示":
                        if each[7].value is None:
                            continue
                        self.drawIndexText(each[3].value, each[4].value, each[7].value,
                                           each[5].value, each[6].value, each[8].value, each[9].value)
                    if each[2].value == "数据变量显示":
                        if each[7].value is None:
                            continue
                        self.drawText(each[3].value, each[4].value, str(each[7].value),
                                      each[5].value, each[6].value, each[8].value, 0)
                    if each[2].value == "变量图标显示" or each[2].value == "动画图标显示":
                        if each[7].value is None:
                            continue
                        self.drawIndexIcon(each[3].value, each[4].value, each[5].value, each[7].value)
                elif start_flag is True:
                    break
            # 保存图片
            pant = QPainter(self.imgShow)
            self.scene_img.render(pant)
            self.imgShow.save(r"{0}\{1}".format(target_dir, background))
            del pant
            del self.imgShow
            self.scene_img.clear()
        self.statusBar.showMessage("转化完成", 3000)
        # self.graphicsView.setScene(self.graphicsView.scene_img)
        # pant = QPainter(self.imgShow)
        # self.graphicsView.scene_img.render(pant)
        # self.imgShow.save(r"C:\Users\lzr\Desktop\20240218021831.png")

        # self.graphicsView.fitInView(QGraphicsPixmapItem(QPixmap(self.imgShow)))  # 图像自适应大小


# Press the green button in the gutter to run the script.
if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    app.setStyle(QStyleFactory.create('Fusion'))
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_Setup()
    ui.setupUi(MainWindow)
    ui.start()
    MainWindow.show()
    sys.exit(app.exec_())

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
